var rest = require('rest');
var wh = require('when');
var logger = require('../utils/logger').logger;

exports.register = function (app) {
    function getTicket(){
        var url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + app.locals.token.value + "&type=jsapi";
        return rest(url).then(function(data){
            var data = JSON.parse(data.entity);
            var value = data.ticket;
            var startTime = Date.now();
            app.locals.ticket = {
                value: value,
                startTime: startTime
            };
            logger.info("ticket:" + app.locals.ticket.value);
            return app.locals.ticket;
        });
    }
    if(!app.locals.token){
        return app.locals.getToken().then(procsessTicket);
    }else{
        var startTime = app.locals.token.startTime;
        var currentTime = Date.now();
        var time = currentTime - startTime;
        if (time > 1.5 * 60 * 60) { // 1.5小时后过期
            return app.locals.getToken().then(procsessTicket);
        }
    }
    return procsessTicket();
    function procsessTicket(){
        if(app.locals.ticket){
            var startTime = app.locals.ticket.startTime;
            var currentTime = Date.now();
            var time = currentTime - startTime;
            if (time > 1.5 * 60 * 60) { // 1.5小时后过期
                return getTicket();
            }else{
                console.log("stored ticket" + app.locals.ticket.value);
                return wh.resolve(app.locals.ticket);
            }
        }else{
            return  getTicket();
        }
    }
}


